import prisma from '@/lib/prisma';
import { Prisma } from '@prisma/client';
import { cache } from 'react';
import { unlink } from 'fs/promises';
import { existsSync } from 'fs';
import path from 'path';

// 直接导出类定义
export class DishService {
  static getAllDishes = cache(async () => {
    try {
      console.log('DishService: Starting to fetch dishes...');
      const dishes = await prisma.dish.findMany({
        orderBy: {
          code: 'asc',
        },
        select: {
          id: true,
          code: true,
          name: true,
          price: true,
          image: true,
          tags: true,
          description: true,
          isToday: true,
        },
      });

      // 确保正确解析 tags
      const formattedDishes = dishes.map(dish => ({
        ...dish,
        tags: typeof dish.tags === 'string' ? JSON.parse(dish.tags) : [],
        key: dish.id // 为 antd Table 添加 key
      }));

      console.log('DishService: Successfully fetched dishes:', formattedDishes);
      return formattedDishes;
    } catch (error) {
      console.error('DishService: Error fetching dishes:', error);
      throw error;
    }
  });

  static async createDish(data: Prisma.DishCreateInput) {
    try {
      const result = await prisma.dish.create({
        data: {
          ...data,
          tags: typeof data.tags === 'string' ? data.tags : JSON.stringify(data.tags || []),
        }
      });

      return {
        ...result,
        tags: typeof result.tags === 'string' ? JSON.parse(result.tags) : result.tags,
      };
    } catch (error) {
      console.error('DishService createDish error:', error);
      throw error;
    }
  }

  static async updateDish(id: string, data: Prisma.DishUpdateInput) {
    return prisma.dish.update({
      where: { id },
      data: {
        ...data,
        tags: typeof data.tags === 'string' ? data.tags : JSON.stringify(data.tags || []),
      },
    });
  }

  static async deleteDish(id: string) {
    try {
      // 先获取菜品信息
      const dish = await prisma.dish.findUnique({
        where: { id },
        select: { image: true }
      });

      if (!dish) {
        throw new Error('菜品不存在');
      }

      // 删除数据库记录
      await prisma.dish.delete({
        where: { id },
      });

      // 删除图片文件
      if (dish.image.startsWith('/uploads/')) {
        const filename = dish.image.split('/').pop();
        if (filename) {
          const filepath = path.join(process.cwd(), 'public', 'uploads', filename);
          if (existsSync(filepath)) {
            await unlink(filepath);
          }
        }
      }

      return { success: true };
    } catch (error) {
      console.error('Delete dish error:', error);
      throw new Error(error instanceof Error ? error.message : '删除失败');
    }
  }

  static async getDishById(id: string) {
    const dish = await prisma.dish.findUnique({
      where: { id }
    });

    if (!dish) return null;

    return {
      ...dish,
      tags: typeof dish.tags === 'string' ? JSON.parse(dish.tags) : dish.tags,
    };
  }
} 